<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<html>
<head>
<title>Simple jsp page</title>
<script type="text/javascript" src="../../resources/js/jquery-1.6.js"></script>
<script type="text/javascript" src="../../resources/js/jquery.form.js"></script>
<script type="text/javascript" src="../../resources/js/jquery-validation-1.8.0/jquery.validate.js"></script>
<script type="text/javascript" src="../../resources/js/jquery-validation-1.8.0/additional-methods.js"></script>
<script type="text/javascript" src="../../resources/js/jquery-ui-1.8.11.custom.min.js"></script>
<script type="text/javascript" src="../../resources/js/fancybox/jquery.fancybox-1.3.4.pack.js"></script>
<script type="text/javascript" src="../../resources/js/fancybox/jquery.easing-1.3.pack.js"></script>
<script type="text/javascript" src="../../resources/js/fancybox/jquery.mousewheel-3.0.4.pack.js"></script>
<link rel="stylesheet" href="../../resources/js/fancybox/jquery.fancybox-1.3.4.css" type="text/css" media="screen"/>
<link rel="stylesheet" type="text/css" media="screen" href="../../resources/css/start/jquery-ui-1.8.10.custom.css"/>
<style type="text/css">
    * {
        font-family: Verdana;
        font-size: 96%;
    }

    label {
        width: 10em;
        float: left;
    }

    label.error {
        float: none;
        color: red;
        padding-left: .5em;
        vertical-align: top;
    }

    fieldset {
        padding: 0px 0px;
        margin: 0px 0px;
    }

    p {
        clear: both;
    }

    .submit {
        margin-left: 12em;
    }

    em {
        font-weight: bold;
        padding-right: 1em;
        vertical-align: top;
    }

    .unread {
        font-weight: bold;
    }

</style>
<script type="text/javascript">
$(document).ready(function() {

    MAILS_PER_PAGE = 20;

    $("#messageTabs").tabs();

    $("#accordionS").accordion({
                collapsible: true,
                change: function(event, ui) {

                },
                //spinner:"Loading message ...",
                alwaysOpen: false,
                clearStyle: true,
                fillspase:true,
                active: false
            });

    $("#accordionR").accordion({
                collapsible: true,
                change: function(event, ui) {
                },
                //spinner:"Loading message ...",
                alwaysOpen: false,
                clearStyle: true,
                fillspase:true,
                active: false
            });

    $("#receivedOlder").button({
                text: false,
                icons: {
                    primary: "ui-icon-circle-arrow-e"
                }
            }).click(function() {
                viewOlderReceivedMessages(MAILS_PER_PAGE);
            })

    $("#receivedNewer").button({
                disabled:true,
                text: false,
                icons: {
                    primary: "ui-icon-circle-arrow-w"
                }
            }).click(function() {
                viewNewerReceivedMessages(MAILS_PER_PAGE);
            })

    $("#sentOlder").button({
                text: false,
                icons: {
                    primary: "ui-icon-circle-arrow-e"
                }
            }).click(function() {
                viewOlderSentMessages(MAILS_PER_PAGE);
            })

    $("#sentNewer").button({
                disabled:true,
                text: false,
                icons: {
                    primary: "ui-icon-circle-arrow-w"
                }
            }).click(function() {
                viewNewerSentMessages(MAILS_PER_PAGE);
            })

    setReceivedMessageToolbar(1, MAILS_PER_PAGE);
    setSentMessageToolbar(1, MAILS_PER_PAGE);

    $('#accordionR h3').click(function(e) {
        getReceivedMessage(e, true);
    });

    $('#accordionS h3').click(function(e) {
        getSentMessage(e, false);
    });

});

function getReceivedMessage(e, markAsRead) {
    if ($(e.currentTarget).next().text().trim().length == 0) {
        $(e.target).removeClass("unread");

        $.getJSON('/messages/' + e.currentTarget.id, {markAsRead:markAsRead}, function(data) {

            var innerText = data.text;
            innerText = innerText.split("\n").join("<br/>");
            innerText = innerText + "<br/><a class=\"replyClass\" style=\"margin-left:10em\" href=\"/messages/create?receiver=" + data.sender.email + "\">ответить</a>"
            $(e.currentTarget).next().append(innerText);
            $(".replyClass").fancybox({
                        'width'             : '50%',
                        'height'            : '50%',
                        'autoScale'         : false,
                        'transitionIn'      : 'none',
                        'transitionOut'     : 'none',
                        'type'              : 'iframe'
                    });

        });
    }
}
;

function getSentMessage(e, markAsRead) {
    if ($(e.currentTarget).next().text().trim().length == 0) {
        $(e.target).removeClass("unread");
        $.getJSON('/messages/' + e.currentTarget.id, {markAsRead:markAsRead}, function(data) {
            $(e.currentTarget).next().append(data.text);
        });
    }
}
;

function closeIframe(reload) {
    if (reload) {
        window.location.reload();
    }
    $('#fancybox-wrap').hide('slow').remove();
    $('#fancybox-overlay').hide('slow').remove();

}

function setReceivedMessageToolbar(offset, shift) {


    $("#receivedFrom").text(offset);

    if ($("#receivedFrom").text() == "1") {
        $("#receivedNewer").button({disabled:true})
    }
    ;

    if (offset + shift - 1 < $("#receivedAmount").text()) {
        $("#receivedTo").text(offset + shift - 1);
    } else {
        $("#receivedTo").text($("#receivedAmount").text());
        $("#receivedOlder").button({disabled:true})
    }


    loadReceivedMessages(offset, shift);

}

function setSentMessageToolbar(offset, shift) {
    $("#sentFrom").text(offset);
    if ($("#sentFrom").text() == "1") {
        $("#sentNewer").button({disabled:true})
    }
    ;

    if (offset + shift - 1 < $("#sentAmount").text()) {
        $("#sentTo").text(offset + shift - 1);
    } else {
        $("#sentTo").text($("#sentAmount").text());
        $("#sentOlder").button({disabled:true})
    }

    loadSentMessages(offset, shift);
}

function viewNewerReceivedMessages(amount) {
    $("#receivedOlder").button({disabled:false})
    viewReceivedMessages(-amount);

}

function viewOlderReceivedMessages(amount) {
    $("#receivedNewer").button({disabled:false});
    viewReceivedMessages(amount);
}

function viewReceivedMessages(shift) {
    var from = $("#receivedFrom").text();
    setReceivedMessageToolbar(parseInt(from) + parseInt(shift), MAILS_PER_PAGE);
}

function viewNewerSentMessages(amount) {
    $("#receivedOlder").button({disabled:false})
    viewSentMessages(-amount);

}

function viewOlderSentMessages(amount) {
    $("#receivedNewer").button({disabled:false});
    viewSentMessages(amount);
}

function viewSentMessages(shift) {
    var from = $("#receivedFrom").text();
    setSentMessageToolbar(parseInt(from) + parseInt(shift), MAILS_PER_PAGE);
}

function loadReceivedMessages(offset, amount) {
    $("#accordionR").empty();
    $.getJSON('/messages/received', {offset:offset, amount:amount}, function(data) {
        $.each(data, function(key, value) {

            var date = new Date(value.time);
            var innerHtml;
            if (value.read) {
            innerHtml = "<h3 id=\"" + value.idMail + "\">"
                    + "<a href=\"#\">От : " + value.sender.firstName + " " + value.sender.lastName
                    + " Тема : " + value.subject + " Отправлено : " + date + "</a></h3>" +
                    "<div><p></p></div>";
            } else {
                innerHtml = "<h3 id=\"" + value.idMail + "\">"
                    + "<a href=\"#\"><b>От : " + value.sender.firstName + " " + value.sender.lastName
                    + " Тема : " + value.subject + " Отправлено : " + date + "</b></a></h3>" +
                    "<div><p></p></div>";
            }
            $("#accordionR").append(innerHtml).accordion('destroy').accordion(
                    {
                        collapsible: true,
                        change: function(event, ui) {
                        },
                        alwaysOpen: false,
                        clearStyle: true,
                        fillspase:true,
                        active: false
                    });
        });
        $('#accordionR h3').click(function(e) {
            getReceivedMessage(e, true);
        });


    });


}

function loadSentMessages(offset, amount) {
    $("#accordionS").empty();
    $.getJSON('/messages/sent', {offset:offset, amount:amount}, function(data) {
        $.each(data, function(key, value) {

            var date = new Date(value.time);
            $("#accordionS").append("<h3 id=\"" + value.idMail + "\">"
                    + "<a href=\"#\">Адресат : " + value.receiver.firstName + " " + value.receiver.lastName
                    + " Тема : " + value.subject + " Отправлено : " + date + "</a></h3>" +
                    "<div><p></p></div>"
            ).accordion('destroy').accordion({
                        collapsible: true,
                        change: function(event, ui) {
                        },
                        alwaysOpen: false,
                        clearStyle: true,
                        fillspase:true,
                        active: false
                    });
        });

        $('#accordionS h3').click(function(e) {
            getSentMessage(e, false);
        });

    });


}


</script>
</head>
<body>
<jsp:useBean id="dateValue" class="java.util.Date"/>

<div id="messageTabs">
    <ul>
        <li><a href="#receivedTab">Входящие сообщение</a></li>
        <li><a href="#sendedTab">Отправленные сообщения</a></li>
    </ul>

    <div id="receivedTab">
        <div id="receivedToolbar">
            <span id="receivedFrom"></span>
            -
            <span id="receivedTo"></span>
            of
            <span id="receivedAmount">${amountOfReceivedMessages}</span>
            <span><button id="receivedNewer">новее</button></span>
            <span><button id="receivedOlder">старее</button></span>
        </div>
        <div id="accordionR">
            <c:forEach var="message" items="${receivedMessages}">
                <jsp:setProperty name="dateValue" property="time" value="${message.time}"/>
                <c:choose>
                    <c:when test="${message.read }">
                        <h3 id="${message.idMail }"><a href="#">От:${message.sender.email }
                            Тема:${message.subject } Отправлено:<fmt:formatDate
                                    value="${dateValue}" pattern="MM/dd/yyyy HH:mm"/>
                        </a>

                        </h3>
                    </c:when>
                    <c:otherwise>
                        <h3 id="${message.idMail }"><b><a href="#">От:${message.sender.email }
                            Тема:${message.subject } Отправлено:<fmt:formatDate
                                    value="${dateValue}" pattern="MM/dd/yyyy HH:mm"/>
                        </a>
                        </b>

                        </h3>
                    </c:otherwise>
                </c:choose>


                <div>
                    <p>
                            <%-- ${message.text } --%>
                    </p>
                </div>
            </c:forEach>
        </div>
    </div>
    <div id="sendedTab">
        <div id="sentToolbar">
            <span id="sentFrom"></span>
            -
            <span id="sentTo"></span>
            of
            <span id="sentAmount">${amountOfSentMessages}</span>
            <span><button id="sentNewer">newer</button></span>
            <span><button id="sentOlder">older</button></span>
        </div>
        <div id="accordionS">
            <c:forEach var="message" items="${sendedMessages}">
                <jsp:setProperty name="dateValue" property="time" value="${message.time}"/>
                <c:choose>
                    <c:when test="${message.read }">
                        <h3 id="${message.idMail }"><a href="#">Адресат:${message.receiver.email }
                            Тема:${message.subject } Отправлено:<fmt:formatDate
                                    value="${dateValue}" pattern="MM/dd/yyyy HH:mm"/>
                        </a>

                        </h3>
                    </c:when>
                    <c:otherwise>
                        <h3 id="${message.idMail }"><b><a href="#">Адресат:${message.receiver.email }
                            Тема:${message.subject } Отправлено:<fmt:formatDate
                                value="${dateValue}" pattern="MM/dd/yyyy HH:mm"/>
                        </b></a>

                        </h3>
                    </c:otherwise>
                </c:choose>


                <div>
                    <p>
                            <%--  ${message.text } --%>
                    </p>
                </div>
            </c:forEach>
        </div>
    </div>
</div>
</body>
</html>